#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "mqmclient.hpp"

using namespace topconn;

void Usage(int argc,char* argv[])
{
    printf("Usage1:%s qmName qName qMsgfile \n",argv[0]);
    printf("Usage2:%s qmName qName qMsgfile qConnectName qChannel(default:SYSTEM.DEF.SVRCONN) \n",argv[0]);
    return;
}

int QRecv(const char* psQMName,const char* psQName,const char* psConnectName,const char* psChannel,FILE* hFile)
{
    MqmClient mqClient;
    mqClient.setQmName(psQMName);
    mqClient.setQConnectName(psConnectName);
    mqClient.setQChannel(psChannel);
    mqClient.setQname(psQName);
    if(mqClient.connect() != 0)
    {
        printf( "MQconnect error! ThreadID [%ld] exit.\n",  pthread_self());
        return -1;
    }

    if (mqClient.openQueue() != 0)
    {
        printf("openQueue error! ThreadID [%ld] exit.\n", pthread_self());
        return -1;
    }

    while(1)
    {
        std::string data;
        if( mqClient.get(data) != 0)
        {
            if (mqClient.reasonCode() == MQRC_NO_MSG_AVAILABLE)
            {
                printf("mqget MQRC_NO_MSG_AVAILABLE\n");
                break;
            }              
            printf("mqget ERROR\n");
            break;
        }      
        printf("MQGET_BUF=[%d][%s]\n",data.size(),data.c_str());
        if(hFile)
        {
            fprintf(hFile,"=================BEGIN==================\n");
            fprintf(hFile,"DATA_LENGTH=%d\n",data.size());
            fprintf(hFile,"DATA=[\n");
            fprintf(hFile,"%s\n",data.c_str());
            fprintf(hFile,"]\n");
            fprintf(hFile,"=================END==================\n\n");
        }
    } 
    return 0;
}

int main(int argc,char* argv[])
{
    if(argc != 4 && argc != 5 && argc != 6)
    {
        Usage(argc,argv);
        return -1;
    }
    
    char sQMName[40] = {0};
    char sQName[40] = {0};
    char sQMsgfile[128] = {0};
    char sQChannel[40] = {0};
    char sQConnectName[80] = {0};

    strcpy(sQMName,argv[1]);
    strcpy(sQName,argv[2]);
    strcpy(sQMsgfile,argv[3]);

    if(argc == 5)
    {
        strcpy(sQConnectName,argv[4]);
        strcpy(sQChannel, "SYSTEM.DEF.SVRCONN");
    }
    else if(argc == 6)
    {
        strcpy(sQConnectName,argv[4]);
        strcpy(sQChannel,argv[5]);
    }    

    FILE* hFile = fopen(sQMsgfile,"w+");
    if(hFile == NULL)
    {
        printf("fopen error:%s\n",strerror(errno));
        return -1;
    }
    QRecv(sQMName,sQName,sQConnectName,sQChannel,hFile);
    if(hFile)
    {
        fclose(hFile);
    }
    return 0;
}